import React, { FC } from 'react';
import ProTable, { ProColumns, ActionType } from '@/components/ProTable';
import styles from './index.less';
import { useModel } from 'umi';
import { TableListItem } from '@/pages/Card/useCardModel';
import ToolBar from './components/Toolbar';
import IconFont from '@/components/IconFont';
import ModalContent from './components/Modal';
import useAuthorityHoxModel from '@/pages/Authority/useHoxModel';
import useHoxModel from '../../useHoxModel';
import { modelName } from '../../index';
import { useUpdateEffect } from 'ahooks';
import { Modal, Dropdown, Menu } from 'antd';
import ConfirmProps from '@/components/CommonModal/Confirm';

const { confirm } = Modal;

//定义setTimeout返回类型
// type TimerHandle = ReturnType<typeof setTimeout>;

interface CardProps {
  actionRef: React.MutableRefObject<ActionType | undefined>;
}

const BlankCard: FC<CardProps> = ({ actionRef }) => {
  const {
    getDoorList,
    getDoorInfo,
    currentCode,
    deleteDoor,
    selectedRowKeys,
    getControllerType,
    getDoorOpenType,
    getPlanMode,
    dispatch,
    isShowControllerTable,
  } = useHoxModel((model) => [
    model.isShowControllerTable,
    model.selectedRowKeys,
    model.currentCode,
  ]);
  const { showModal } = useModel('useCommonModal', (model) => ({ showModal: model.showModal }));

  const { getCardUserListByDoor, getUserFormAreaList } = useAuthorityHoxModel((model) => []);
  useUpdateEffect(() => {
    actionRef.current?.reloadAndRest();
  }, [currentCode]);

  const menu = (record: { id: number }) => {
    const onClick = async ({ key }: { key: string }) => {
      switch (key) {
        case 'permissionsConfig':
          dispatch({ info: record });
          getUserFormAreaList();
          getCardUserListByDoor({ id: record.id });
          showModal(modelName + 'permissionsConfig');
          break;
        case 'permissionsDetail':
          dispatch({ info: record });
          showModal(modelName + 'detail');
          break;
        case 'edit':
          getDoorInfo({ id: Number(record['id']) });
          getDoorOpenType();
          getControllerType();
          getPlanMode();
          showModal(modelName + 'edit');
          break;
        case 'alarmInfo':
          dispatch({ info: record });
          showModal(modelName + 'alarmInfo');

          break;
        case 'openDoorRecord':
          dispatch({ info: record });
          showModal(modelName + 'openDoorRecord');

          break;
        case 'delete':
          confirm({
            ...new ConfirmProps(),
            async onOk() {
              let res = await deleteDoor({ ids: [Number(record['id'])] });
              if (res.result === 0) {
                actionRef.current?.reloadAndRest();
              }
            },
          });
          break;
        case 'timeCalibration':
          dispatch({ info: record });
          showModal(modelName + 'timeCalibration');
          break;
      }
    };
    return (
      <Menu onClick={onClick}>
        <Menu.Item key={'edit'}>
          <IconFont type={'iconbianji'} style={{ fontSize: '14px' }} />
          <span>编辑</span>
        </Menu.Item>
        <Menu.Item key={'permissionsConfig'}>
          <IconFont type={'iconquanxianpeizhi'} style={{ fontSize: '14px' }} />
          <span>权限配置</span>
        </Menu.Item>
        <Menu.Item key={'permissionsDetail'}>
          <IconFont type={'iconquanxianxiangqing'} style={{ fontSize: '14px' }} />
          <span>权限详情</span>
        </Menu.Item>
        <Menu.Item key={'openDoorRecord'}>
          <IconFont type={'iconkaimenjilu'} style={{ fontSize: '14px' }} />
          <span>开门记录</span>
        </Menu.Item>
        <Menu.Item key={'timeCalibration'}>
          <IconFont type={'iconshijianxiaozhun'} style={{ fontSize: '14px' }} />
          <span>时间校准</span>
        </Menu.Item>
        <Menu.Item key={'alarmInfo'}>
          <IconFont type={'icongaojingxinxi'} style={{ fontSize: '14px' }} />
          <span>告警信息</span>
        </Menu.Item>
        <Menu.Item key={'delete'}>
          <IconFont type={'iconshanchu1'} style={{ fontSize: '14px' }} />
          <span>删除</span>
        </Menu.Item>
      </Menu>
    );
  };
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '门状态',
      dataIndex: 'doorStatus',
      valueEnum: {
        1: { text: '离线' },
        0: { text: '在线' },
        '': { text: '全部' },
      },
      hideInTable: true,
    },
    {
      title: '门名称',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '所在区域',
      align: 'center',
      dataIndex: 'regionName',
      hideInSearch: true,
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '控制器名称',
      align: 'center',
      dataIndex: 'controllerName',
      hideInSearch: true,
    },
    {
      title: '计划模板',
      align: 'center',
      dataIndex: 'planMode',
      hideInSearch: true,
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'status',
      render: (text: React.ReactNode) => {
        const valueEnum = {
          1: '在线',
          0: '离线',
        };
        return (
          <>
            {text !== '-' ? (
              <span className={Number(text) === 0 ? styles['online'] : styles['offline']}>
                {valueEnum[Number(text)]}
              </span>
            ) : (
              '-'
            )}
          </>
        );
      },

      hideInSearch: true,
    },
    {
      title: '操作',
      key: 'option',
      width: '6%',
      valueType: 'option',
      render: (_, record, index) => [
        <Dropdown overlay={menu(record)} key={index.toString(36) + index}>
          <a key={'loss'} className={styles['operation']}>
            <IconFont type={'iconcaozuo2'} />
          </a>
        </Dropdown>,
      ],
    },
  ];
  const ControllerColumns: ProColumns<TableListItem>[] = [
    {
      title: '编号',
      dataIndex: 'id',
      align: 'center',
      hideInSearch: true,
    },
    {
      title: '控制器名称',
      align: 'center',
      dataIndex: 'controllerName',
      hideInSearch: true,
    },
    {
      title: '门名称',
      align: 'center',
      dataIndex: 'name',
    },
    {
      title: '控制器类型',
      align: 'center',
      dataIndex: 'controllerType',
      hideInSearch: true,
    },
    {
      title: 'IP',
      align: 'center',
      dataIndex: 'ip',
      hideInSearch: true,
    },
    {
      title: '端口',
      align: 'center',
      dataIndex: 'port',
      hideInSearch: true,
    },
  ];

  return (
    <div className={styles['container']}>
      <ProTable<TableListItem>
        columns={isShowControllerTable ? ControllerColumns : columns}
        request={async (params: { [key: string]: any }) => {
          const data = await (currentCode &&
            getDoorList({
              keyword: params.name || undefined,
              number: params.pageSize,
              page: params.current,
              code: currentCode,
              status: params.doorStatus || undefined,
            }));
          return await {
            data: (currentCode && data?.list) || [],
            success: true,
            total: (currentCode && data?.count) || 0,
          };
        }}
        rowKey="id"
        rowSelection={{
          selectedRowKeys,
          onChange: (selectedRowKeys) => {
            dispatch({ selectedRowKeys });
          },
        }}
        tableAlertRender={false}
        actionRef={actionRef}
        dateFormatter="string"
        headerTitle={false}
        toolBarRender={() => [<ToolBar actionRef={actionRef} />]}
      />
      <ModalContent actionRef={actionRef} />
    </div>
  );
};
export default BlankCard;
